/*
 * Integer class represents a signed integer restricted to 16-bit
 * Integer is word compatible
 * */


package cpu.datatypes;

public class Integer extends Word {
	private boolean signed = true;

	// Default Constructor
	public Integer( ) {
		super( );
	}
	// Copy Constructor
	public Integer( Integer i ) {
		// can use super here?
		super( i );
	}
	public Integer( int i ) {
		fromJavaInt( i );
	}
	public Integer( Word w ) {
		// can use super here?
		super( w );
	}
	public int toJavaInt( ) {
		if( signed ) {
			int accumulator = 0;

			for( int i = 1; i < 8; i++ ) {
				if( byteLow.bit( i ).value )
					accumulator += java.lang.Math.pow( 2, i - 1 );
			}
			for( int i = 0; i < 8; i++ ) {
				if( byteHigh.bit( i ).value )
					accumulator += java.lang.Math.pow( 2, i - 1 + 8 );
			}
			
			if( byteLow.bit( 0 ).value ) accumulator = -accumulator;
			
			return accumulator;
		} else {
			return super.toJavaInt( );
		}
	}
	public boolean fromJavaInt( int value ) {
		if( signed ) {
			// note return value is overflow
			int accumulator = value;
			
			if( value < 0 ) {
				accumulator = -accumulator;
				byteLow.bit( 0 ).value = true;				
			} else {
				byteLow.bit( 0 ).value = false;
			}
			
			for( int i = 7; i >= 0; i-- ) {
				if( accumulator / (int) java.lang.Math.pow( 2, i - 1 + 8 ) >= 1 ) {
					byteHigh.bit( i ).value = true;
					accumulator -= java.lang.Math.pow( 2, i - 1 + 8 );
				} else {
					byteHigh.bit( i ).value = false;
				}
			}
			for( int i = 7; i >= 1; i-- ) {
				if( accumulator / (int) java.lang.Math.pow( 2, i - 1 ) >= 1 ) {
					byteLow.bit( i ).value = true;
					accumulator -= java.lang.Math.pow( 2, i - 1 );
				} else {
					byteLow.bit( i ).value = false;
				}
			}

			if( accumulator != 0 ) 
				return true;		// overflow
			return false;			// no overflow			
		} else {
			return super.fromJavaInt( value );
		}
	}
}
